package com.itheima.sercuriy;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 如果需要从数据库查询用户信息，必须有一个实现UserDetailsService接口的实现类
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
public class SecurityConfigUserService implements UserDetailsService {
//    模拟数据库数据
    private static Map<String,SysUser> userDb = new HashMap<>();

    static {
        SysUser user1 = new SysUser();
        user1.setUsername("admin");
        user1.setPassword(new BCryptPasswordEncoder().encode("123"));
        // 用户权限与角色
        Role role1 = new Role("系统管理员","ROLE_ADMIN");
        role1.getPermissions().add(new Permission("添加权限","add"));
        role1.getPermissions().add(new Permission("删除权限","delete"));
        role1.getPermissions().add(new Permission("更新权限","update"));
        role1.getPermissions().add(new Permission("查询权限","find"));
        user1.getRoles().add(role1);
        userDb.put(user1.getUsername(),user1);

        SysUser userZhangSan = new SysUser();
        userZhangSan.setUsername("zhangsan");
        userZhangSan.setPassword(new BCryptPasswordEncoder().encode("123"));
        Role role2 = new Role("普通用户","ROLE_USER");;
        role2.getPermissions().add(new Permission("查询权限","find"));
        userZhangSan.getRoles().add(role2);
        userDb.put(userZhangSan.getUsername(),userZhangSan);
    }



    /**
     * 根据用户名载入用户对象
     *  1. 根据用户名查询用户数据
     *  2. 包装UserDetails， 返回给安全框架
     * @param username
     * @return   返回用户对象（UserDetails）
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//       1. 模拟从数据库查询一个用户对象
        SysUser sysUser = userDb.get(username);
        if(sysUser == null){
            return null;
        }

//        创建权限列表
        List<GrantedAuthority> authorityList = new ArrayList<>();
//        遍历角色对象
        for (Role role : sysUser.getRoles()) {
            SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority( role.getKeyword());
            authorityList.add(grantedAuthority);
            //遍历该角色对应的权限
            for (Permission permission : role.getPermissions()) {
                SimpleGrantedAuthority grantedAuthority2 = new SimpleGrantedAuthority( permission.getKeyword());
                authorityList.add(grantedAuthority2);
            }
        }

//        2. 包装UserDetails， 返回给安全框架
        User user = new User(sysUser.getUsername(),sysUser.getPassword(),authorityList );


        return user;
    }
}
